package com.lk.security.authentication.mobile;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;

/**
 * @description:
 * @author: Aspirin
 * @create: 2020-05-31 09:50
 */
public class MobileAuthenticationToken extends AbstractAuthenticationToken {

  private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

  /** 认证前是手机号码，认证后是用户信息 */
  private final Object principal;

  /** 认真之前试用的构造方法，此方法会标识未认证 */
  public MobileAuthenticationToken(Object principal) {
    super(null);
    // 手机号码
    this.principal = principal;
    // 未认证
    setAuthenticated(false);
  }

  /**
   * 认证通过后，会重新创建MobileAuthenticationToken实例，来封装认证信息
   *
   * @param principal 用户信息
   * @param authorities 权限资源
   */
  public MobileAuthenticationToken(
      Object principal, Collection<? extends GrantedAuthority> authorities) {
    super(authorities);
    this.principal = principal;
    super.setAuthenticated(true);
  }

  /**
   * 父类中抽象方法，必须实现，返回null就好了
   *
   * @return Object
   */
  @Override
  public Object getCredentials() {
    return null;
  }

  @Override
  public Object getPrincipal() {
    return this.principal;
  }

  @Override
  public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
    if (isAuthenticated) {
      throw new IllegalArgumentException(
          "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
    }

    super.setAuthenticated(false);
  }

  @Override
  public void eraseCredentials() {
    super.eraseCredentials();
  }
}
